<template>
  <div class="goods-cate-container">
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ name: 'welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addGoodsCate">添加分类</el-button>
        </el-col>
      </el-row>
      <!-- 列表区域--S -->
      <TreeTable
        class="tree-table"
        :data="goodsCateList"
        :columns="goodsCateColumns"
        :show-index="true"
        index-text="#"
        border
        :show-row-hover="false"
        :expand-type="false"
        :selection-type="false"
      >
        <!-- 是否有效 -->
        <template #isValid="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template #order="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template #operate="scope">
          <el-button
            class="el-icon-edit"
            size="mini"
            type="primary"
            @click="editCate(scope.row)"
            >编辑</el-button
          >
          <el-button
            class="el-icon-delete"
            size="mini"
            type="danger"
            @click="deleteCate(scope.row)"
            >删除</el-button
          >
        </template>
      </TreeTable>
      <!-- 列表区域--E -->
      <!-- 分页区域--S -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[3, 5, 8, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
      <!-- 分页区域--E -->
    </el-card>
    <!-- 添加分类的对话框--S -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        :rules="addCateFormRules"
        ref="addCateFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类" prop="cat_pid">
          <el-cascader
            class="parent-cate"
            ref="addCateCascader"
            v-model="parentCateKeys"
            :options="parentCateList"
            :props="parentCateProps"
            @change="handleParentCateChange"
            clearable
          ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCateOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 添加分类的对话框--E -->
    <!-- 编辑分类的对话框--S -->
    <el-dialog
      title="编辑分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
    >
      <el-form
        :model="editCateForm"
        :rules="editCateFormRules"
        ref="editCateFormRef"
        label-width="80px"
      >
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateOnConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑分类的对话框--E -->
  </div>
</template>

<script>
import {
  getGoodsCateAPI,
  addGoodsCateAPI,
  editGoodsCateAPI,
  deleteGoodsCateByIdAPI
} from '@/api'
export default {
  name: 'GoodsCate',
  data() {
    return {
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      goodsCateList: [],
      goodsCateColumns: [
        {
          label: '分类名称',
          prop: 'cat_name'
          // width: '80px'
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isValid'
        },
        {
          label: '排序',
          type: 'template',
          template: 'order'
        },
        {
          label: '操作',
          type: 'template',
          template: 'operate'
        }
      ],
      addCateForm: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      editCateForm: {
        cat_name: ''
      },
      addCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      editCateFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      addCateDialogVisible: false,
      parentCateList: [],
      parentCateKeys: [],
      parentCateProps: {
        label: 'cat_name',
        value: 'cat_id',
        children: 'children',
        checkStrictly: true
      },
      editCateDialogVisible: false,
      cateId: 0
    }
  },
  created() {
    this.loadingGoodsCate()
  },
  methods: {
    // 加载商品分类列表
    async loadingGoodsCate() {
      try {
        const { data } = await getGoodsCateAPI(this.queryInfo)
        // console.log(data)
        if (data.meta.status !== 200) {
          return this.$message.error('获取商品分类列表失败')
        }
        this.total = data.data.total
        const { result } = data.data
        this.goodsCateList = result
      } catch (err) {
        this.$message.error('获取商品分类列表失败')
      }
    },
    //  监听分页每页大小改变
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.loadingGoodsCate()
    },
    //  监听切换页面事件
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.loadingGoodsCate()
    },
    //  添加分类
    async addGoodsCate() {
      try {
        const { data } = await getGoodsCateAPI({ type: 2 })
        if (data.meta.status !== 200) {
          return this.$message.error('获取父级分类失败')
        }
        // console.log(data)
        this.parentCateList = data.data
      } catch (err) {
        this.$message.error('获取父级分类失败')
      }
      this.addCateDialogVisible = true
    },
    //  optiops 中父级分类选项改变监听
    handleParentCateChange() {
      if (this.parentCateKeys.length > 0) {
        this.addCateForm.cat_pid = this.parentCateKeys.slice(-1)[0]
        this.addCateForm.cat_level = this.parentCateKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
    },
    // 监听对话框的关闭事件
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields()
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
      this.parentCateKeys = []
    },
    // 监听确认添加分类事件
    addCateOnConfirm() {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        try {
          const { data } = await addGoodsCateAPI(this.addCateForm)
          if (data.meta.status !== 201) {
            return this.$message.error('添加分类失败')
          }
          this.$message.success('添加分类成功')
          this.addCateDialogVisible = false
          this.loadingGoodsCate()
        } catch (err) {
          this.$message.error('添加分类失败')
        }
      })
    },
    // 编辑分类
    editCate(cate) {
      this.editCateForm.cat_name = cate.cat_name
      this.cateId = cate.cat_id
      this.editCateDialogVisible = true
    },
    // 编辑分类确认事件
    editCateOnConfirm() {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return
        try {
          const { data } = await editGoodsCateAPI(
            this.cateId,
            this.editCateForm
          )
          if (data.meta.status !== 200) {
            return this.$message.error('编辑分类失败')
          }
          this.$message.success('编辑分类成功')
          this.editCateDialogVisible = false
          this.loadingGoodsCate()
        } catch (err) {
          this.$message.error('编辑分类失败')
        }
      })
    },
    // 删除分类
    async deleteCate(cate) {
      this.cateId = cate.cat_id
      const res = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // console.log(res)
      if (res !== 'confirm') {
        this.$message.info('已取消删除该分类')
      }
      // 确认删除，渲染页面
      try {
        const { data } = await deleteGoodsCateByIdAPI(this.cateId)
        if (data.meta.status !== 200) {
          return this.$message.error('删除分类失败')
        }
        this.$message.success('删除分类成功')
        this.loadingGoodsCate()
      } catch (err) {
        this.$message.error('删除分类失败')
      }
    }
  }
}
</script>

<style scoped lang="less">
.goods-cate-container {
  .tree-table {
    margin: 15px auto;
  }
  .parent-cate {
    width: 100%;
  }
}
</style>
